package com.haitaoit.chengquan.module.home.activity.parts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.parts.PartsDownAdapter;
import com.haitaoit.chengquan.module.home.adapter.parts.PartsGridAdapter;
import com.haitaoit.chengquan.module.home.adapter.parts.PartsListAdapter;
import com.haitaoit.chengquan.module.home.model.PartsModel;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PartsActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.list_type_img)
    ImageView               list_type_img;
    @ViewInject(R.id.parts_parts_img)
    ImageView               parts_parts_img;
    @ViewInject(R.id.parts_zonghell)
    TextView                parts_zonghell;
    @ViewInject(R.id.parts_xiaoliangtv)
    TextView                parts_xiaoliangtv;
    @ViewInject(R.id.part_serach)
    EditText                part_serach;
    @ViewInject(R.id.jiage_img1)
    ImageView               jiage_img1;
    @ViewInject(R.id.jiage_img2)
    ImageView               jiage_img2;
    @ViewInject(R.id.jiage_img3)
    ImageView               jiage_img3;
    @ViewInject(R.id.jiage_img4)
    ImageView               jiage_img4;
    @ViewInject(R.id.parts_jiagetv)
    TextView                parts_jiagetv;
    @ViewInject(R.id.part_text)
    TextView                part_text;
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView   mScrollView;
    private LinearLayout null_information_layout;
    private MyListView   listView;
    private MyGridView   gridView;


    private boolean isFrist   = true;
    private int     page      = 1;
    private int     list_type = 1;
    private View             view;
    private PopupWindow      myPopWindow;
    private PartsDownAdapter downAdapter;// 品牌
    private PartsListAdapter listAdapter;
    private PartsGridAdapter gridAdapter;
    private List<TitleModel> titleList = new ArrayList<>();
    private String           getid     = "", selectId = "", sorting = "1";//首页类型id 品牌id  综合销量价格排序

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parts);
        ViewUtils.inject(this);

        setListView();
        getid = selectId = getIntent().getStringExtra("selectId");

        if (getid==null){
            getid = "";
        }
        if (TextUtils.equals(getid,"1")){
            part_text.setText("类型");
        }else if (TextUtils.equals(getid,"2")){
            part_text.setText("类型");
        }else {
            part_text.setText("类型");
        }

        httpGetaccessories_goods_class_list();
    }

    public void setListView() {
        if (list_type == 1) {
            view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
            null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
            listView = (MyListView) view.findViewById(R.id.scrollview_listview);

            listAdapter = new PartsListAdapter(this);
            listAdapter.setBackCall(new BackCall() {
                @Override
                public void deal(int which, Object... obj) {
                    int position = (Integer) obj[0];
                    Intent intent = new Intent();
                    switch (which) {
                        case R.id.part_list_itemll:
                            intent.setClass(PartsActivity.this, PartsDetailActivity.class);
                            intent.putExtra("id", listAdapter.getList().get(position).getId());
                            startActivity(intent);
                            break;
                    }
                    super.deal(which, obj);
                }
            });
            listView.setAdapter(listAdapter);
        } else if (list_type == 2) {
            view = LayoutInflater.from(this).inflate(R.layout.scrollview_gridview_layout, null);
            null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
            gridView = (MyGridView) view.findViewById(R.id.scrollview_gridview);
            gridView.setNumColumns(2);
            gridView.setPadding(0, 0, 0, 0);

            gridAdapter = new PartsGridAdapter(this);
            gridAdapter.setBackCall(new BackCall() {
                @Override
                public void deal(int which, Object... obj) {
                    int position = (Integer) obj[0];
                    Intent intent = new Intent();
                    switch (which) {
                        case R.id.part_grid_itemll:
                            intent.setClass(PartsActivity.this, PartsDetailActivity.class);
                            intent.putExtra("id", gridAdapter.getList().get(position).getId());
                            startActivity(intent);
                            break;
                    }
                    super.deal(which, obj);
                }
            });
            gridView.setAdapter(gridAdapter);
        }

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);
    }

    @OnClick({R.id.left, R.id.part_serachgo, R.id.list_type_img, R.id.parts_zonghell,
            R.id.parts_xiaoliangll, R.id.parts_jiagell, R.id.parts_partsll,})
    public void onClick(View v) {// 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.part_serachgo:// 搜索
                if (part_serach.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入搜索内容！");
                } else {
                    isFrist = true;
                    page = 1;
                    httpGetaccessories_goods_list();
                }
                break;
            case R.id.list_type_img:// 切换布局
                if (list_type == 1) {
                    list_type_img.setImageResource(R.mipmap.img30_1);
                    list_type = 2;
                    mScrollView.removeAllViews();
                    setListView();
                    mScrollView.scrollTo(0, 0);
                } else if (list_type == 2) {
                    list_type_img.setImageResource(R.mipmap.img30);
                    list_type = 1;
                    mScrollView.removeAllViews();
                    setListView();
                    mScrollView.scrollTo(0, 0);
                }
                isFrist = true;
                page = 1;
                httpGetaccessories_goods_list();
                break;
            case R.id.parts_zonghell:// 综合
                jiage_img1.setImageResource(R.mipmap.img33_1);
                jiage_img2.setImageResource(R.mipmap.img34_1);
                jiage_img3.setImageResource(R.mipmap.img33_1);
                jiage_img4.setImageResource(R.mipmap.img34_1);
                parts_zonghell.setTextColor(getResources().getColor(R.color.app_color));
                parts_xiaoliangtv.setTextColor(getResources().getColor(R.color.black_text));
                parts_jiagetv.setTextColor(getResources().getColor(R.color.black_text));

                sorting = "1";
                isFrist = true;
                page = 1;
                httpGetaccessories_goods_list();
                break;
            case R.id.parts_xiaoliangll:// 销量
                jiage_img1.setImageResource(R.mipmap.img33_1);
                jiage_img2.setImageResource(R.mipmap.img34_1);
                parts_zonghell.setTextColor(getResources().getColor(R.color.black_text));
                parts_xiaoliangtv.setTextColor(getResources().getColor(R.color.app_color));
                parts_jiagetv.setTextColor(getResources().getColor(R.color.black_text));

                if (sorting.equals("2")) {
                    sorting = "3";
                    jiage_img3.setImageResource(R.mipmap.img33_1);
                    jiage_img4.setImageResource(R.mipmap.img34);
                } else {
                    sorting = "2";
                    jiage_img3.setImageResource(R.mipmap.img33);
                    jiage_img4.setImageResource(R.mipmap.img34_1);
                }
                isFrist = true;
                page = 1;
                httpGetaccessories_goods_list();
                break;
            case R.id.parts_jiagell:// 价格
                jiage_img3.setImageResource(R.mipmap.img33_1);
                jiage_img4.setImageResource(R.mipmap.img34_1);
                parts_zonghell.setTextColor(getResources().getColor(R.color.black_text));
                parts_xiaoliangtv.setTextColor(getResources().getColor(R.color.black_text));
                parts_jiagetv.setTextColor(getResources().getColor(R.color.app_color));
                if (sorting.equals("4")) {
                    sorting = "5";
                    jiage_img1.setImageResource(R.mipmap.img33_1);
                    jiage_img2.setImageResource(R.mipmap.img34);
                } else {
                    sorting = "4";
                    jiage_img1.setImageResource(R.mipmap.img33);
                    jiage_img2.setImageResource(R.mipmap.img34_1);
                }
                isFrist = true;
                page = 1;
                httpGetaccessories_goods_list();
                break;
            case R.id.parts_partsll:// 品牌
                parts_parts_img.setImageResource(R.mipmap.img33);
                iniPopupWindow();
                myPopWindow.showAsDropDown(parts_zonghell, 0, 0);
                break;
        }
        super.onClick(v);
    }

    private void httpGetaccessories_goods_list() {
        if (selectId.equals("")) {// 品牌id
            selectId = getid;
        }

        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("name", part_serach.getText().toString()));
        list.add(new NameValuePairSign("sorting", sorting));
        list.add(new NameValuePairSign("goods_class", selectId));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", part_serach.getText().toString());
        params.addQueryStringParameter("sorting", sorting);
        params.addQueryStringParameter("goods_class", selectId);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getaccessories_goods_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<PartsModel> new_list = new ArrayList<PartsModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PartsModel>();
                            hideProgree();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<PartsModel>>() {
                                    }.getType());
                            hideProgree();
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PartsModel>();
                            hideProgree();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            if (list_type == 1) {
                                listAdapter.setList(new_list);
                                listAdapter.notifyDataSetChanged();
                            } else {
                                gridAdapter.setList(new_list);
                                gridAdapter.notifyDataSetChanged();
                            }
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        if (list_type == 1) {
                            List<PartsModel> allList = listAdapter.getList();
                            allList.addAll(new_list);
                            listAdapter.setList(allList);
                            listAdapter.notifyDataSetChanged();
                        } else {
                            List<PartsModel> allList = gridAdapter.getList();
                            allList.addAll(new_list);
                            gridAdapter.setList(new_list);
                            gridAdapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }

        });
    }

    // 品牌
    private void httpGetaccessories_goods_class_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("type_id", selectId));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type_id", selectId);
        params.addQueryStringParameter("sign", sign);
        showProgrees("加载中，请稍等....");
        HttpUtilsSingle.doGet(this, false, Constant.Getaccessories_goods_class_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            hideProgree();
                            return;
                        case 0:// 成功
                            List<TitleModel> list = gson.fromJson(Response,
                                    new TypeToken<List<TitleModel>>() {
                                    }.getType());
                            //                            if (!selectId.equals("") && selectId.length() != 0) {
                            //                                String[] sele = selectId.split(",");
                            //                                for (int i = 0; i < list.size(); i++) {
                            //                                    for (int j = 0; j < sele.length; j++) {
                            //                                        if (list.get(i).getId().equals(sele[j])) {
                            //                                            titleList.add(new TitleModel(list.get(i).getId(), list.get(i).getName(), true));
                            //                                        } else {
                            //                                            titleList.add(new TitleModel(list.get(i).getId(), list.get(i).getName(), false));
                            //                                        }
                            //                                    }
                            //                                }
                            //                            } else {
                            for (int i = 0; i < list.size(); i++) {
                                titleList.add(new TitleModel(list.get(i).getId(), list.get(i).getName(), false));
                            }
                            //                            }
                            httpGetaccessories_goods_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    // 弹出框
    private void iniPopupWindow() {
        View layout = LayoutInflater.from(this).inflate(R.layout.parts_down_item, null);
        layout.findViewById(R.id.parts_dismiss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myPopWindow.dismiss();
            }
        });
        // 重置
        layout.findViewById(R.id.parts_down_clean).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < titleList.size(); i++) {
                    titleList.get(i).setSelect(false);
                }
                downAdapter.setList(titleList);
                downAdapter.notifyDataSetChanged();
                selectId = "";
            }
        });
        // 确定
        layout.findViewById(R.id.parts_down_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sid = "";
                for (int i = 0; i < titleList.size(); i++) {
                    if (titleList.get(i).isSelect()) {
                        sid = sid + titleList.get(i).getId() + ",";
                    }
                }
                myPopWindow.dismiss();
                if (!sid.equals("") && sid.length() != 0) {
                    selectId = sid.substring(0, sid.length() - 1);
                } else {
                    selectId = "";
                }
                isFrist = true;
                page = 1;
                httpGetaccessories_goods_list();

            }
        });
        GridView parts_dwom_grid = (GridView) layout.findViewById(R.id.parts_dwom_grid);
        downAdapter = new PartsDownAdapter(this);
        downAdapter.setList(titleList);
        if (titleList.size() >= 3) {
            parts_dwom_grid.setNumColumns(3);
            for (int i = 0; i < titleList.size(); i++) {
                if (titleList.get(i).getName().length() >= 6) {
                    parts_dwom_grid.setNumColumns(2);
                    break;
                }
            }
        }
        parts_dwom_grid.setAdapter(downAdapter);

        myPopWindow = new PopupWindow(layout);
        myPopWindow.setFocusable(true); // 加上这个popupwindow中的ListView才可以接收点击事件
        // 控制popupwindow 的宽度和高度
        myPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        myPopWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);

        // 控制popupwindow 点击屏幕其他地方消失
        myPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.color.transparent)); // 设置背景图片,不能在布局中设置，要通过代码来设置
        myPopWindow.setOutsideTouchable(true);
        // 触摸popupwindow外部,popupwindow消失,这个要求你的popupwindow要有背景图片才可以成功
        myPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                parts_parts_img.setImageResource(R.mipmap.img34_1);
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<PartsModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetaccessories_goods_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetaccessories_goods_list();
    }
}
